package com.colter.project.sample.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;

public class SingleFileHttpServer extends Thread {
	private byte[] content;
	private byte[] header;
	private int port = 80;

	public SingleFileHttpServer(String data, String encoding, String MIMEType, int port)
			throws UnsupportedEncodingException {
		this(data.getBytes(encoding), encoding, MIMEType, port);
	}

	public SingleFileHttpServer(byte[] data, String encoding, String MIMEType, int port) {
		this.content = data;
		this.port = port;
		String header = "HTTP/1.0 200 OK\r\n" + "Server: OneFile 1.0 \r\n" + "Content-length:" + this.content.length
				+ "\r\n" + "Content-type: " + MIMEType + "\r\n\r\n";
		this.header = header.getBytes();
	}

	@Override
	public void run() {
		ServerSocket serverSocket = null;
		Socket connection = null;
		try {
			serverSocket = new ServerSocket(this.port);
			System.out.println("Accept connetions on port " + serverSocket.getLocalPort());
			System.out.println("Data to be send:" + new String(this.content));
			while (true) {
				connection = serverSocket.accept();
				OutputStream out = new BufferedOutputStream(connection.getOutputStream());
				InputStream in = new BufferedInputStream(connection.getInputStream());
				StringBuffer request = new StringBuffer();
				while (true) {
					int c = in.read();
					if (c == '\r' || c == '\n' || c == -1) {
						break;
					}
					request.append((char) c);

				}
				if (request.toString().indexOf("HTTP/") != -1) {
					out.write(this.header);
				}

				out.write(this.content);
				out.flush();
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		String contentType = "text/html;charset=utf-8";
		InputStream in = null;
		ByteArrayOutputStream bo = null;
		try {
			in = new FileInputStream("d:\\test.txt");
			bo = new ByteArrayOutputStream();
			int b;
			while ((b = in.read()) != -1) {
				bo.write(b);
			}

			byte[] data = bo.toByteArray();
			int port = 80;
			String encoding = "UTF-8";
			Thread t = new SingleFileHttpServer(data, encoding, contentType, port);
			t.start();

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bo.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
}
